package com.ruoyi.web.controller.system;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.FeeNote;
import com.ruoyi.system.domain.SysNoteCount;
import com.ruoyi.system.service.IFeeNoteService;
import com.ruoyi.system.service.ISysNoteCountService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.utils.NumberParserUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2023-11-01
 */
@RestController
@RequestMapping("/system/note")
public class FeeNoteController extends BaseController
{
    @Resource
    private IFeeNoteService feeNoteService;

    @Resource
    private ISysUserService sysUserService;

    @GetMapping("/download/{id}")
    public AjaxResult download(@PathVariable("id") Long id) throws IOException {
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (sysUser == null) {
            return error("当前用户不存在");
        }
        FeeNote feeNote = feeNoteService.selectFeeNoteById(id);
        if (feeNote != null) {
//            String inputFileName = RuoYiConfig.getDownloadPath() + "fee_model_fixzxc123.pdf";
            String inputFileName = RuoYiConfig.getDownloadPath() + "fee_model_fixzxc123.pdf";
            // 模板文件路径
            // 生成的文件路径 System.currentTimeMillis()
            String timeStr = System.currentTimeMillis() + "";
            timeStr = timeStr.substring(timeStr.length() - 5, timeStr.length());
            String outputFileName = RuoYiConfig.getDownloadPath() + "note_" + timeStr + ".pdf";
            OutputStream os = null;
            PdfStamper ps = null;
            PdfReader reader = null;
            PdfStamper stamper = null;

            try {
                os = new FileOutputStream(new File(outputFileName));
                // 2 读入pdf表单
                reader = new PdfReader(inputFileName);
                // 3 根据表单生成一个新的pdf
                ps = new PdfStamper(reader, os);
                // 4 获取pdf表单
                AcroFields form = ps.getAcroFields();
                // 5给表单添加中文字体
                BaseFont bf = BaseFont.createFont("Font/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                form.addSubstitutionFont(bf);
                String fileName = "";
                if (!StringUtils.isBlank(feeNote.getFilePath())) {
                    URI uri = new URI(feeNote.getFilePath());
                    fileName = uri.getPath().substring(uri.getPath()
                            .lastIndexOf('/') + 1);
                }
                // 6查询数据================================================
                Map<String, Object> data = new HashMap<String, Object>();
                if (!StringUtils.isBlank(feeNote.getClientName())) {
                    data.put("company", feeNote.getClientName());
                } else {
                    data.put("company", "UnKnow");
                }
                if (!StringUtils.isBlank(feeNote.getAmount())) {
                    data.put("amount", NumberParserUtils.fmtMicrometer(feeNote.getAmount()));
                    data.put("monSal", NumberParserUtils.fmtMicrometer(feeNote.getAmount()));
                } else {
                    data.put("amount", NumberParserUtils.fmtMicrometer("0"));
                    data.put("monSal", NumberParserUtils.fmtMicrometer("0"));
                }
                if (!StringUtils.isBlank(feeNote.getAddressLine1())) {
                    data.put("address", feeNote.getAddressLine1());
                } else {
                    data.put("address", "unknow");
                }
                if (!StringUtils.isBlank(feeNote.getDiscounted())) {
                    data.put("discount", feeNote.getDiscounted() + "%");
                } else {
                    data.put("discount", 0);
                }
                if (!StringUtils.isBlank(feeNote.getFeeNo())) {
                    data.put("feeNo", feeNote.getFeeNo());
                } else {
                    data.put("feeNo", "unknow");
                }
                if (feeNote.getFeeAmt() == null) {
                    data.put("netAmount", NumberParserUtils.fmtMicrometer("0"));
                    data.put("netAmount2", "HK$" + NumberParserUtils.fmtMicrometer("0"));
                } else {
                    data.put("netAmount", NumberParserUtils.fmtMicrometer(String.valueOf(feeNote.getFeeAmt())));
                    data.put("netAmount2", "HK$" + NumberParserUtils.fmtMicrometer(String.valueOf(feeNote.getFeeAmt())));
                }
                //
                if (!StringUtils.isBlank(feeNote.getAttn())) {
                    data.put("name", feeNote.getAttn());
                } else {
                    data.put("name", "unknow");
                }
                if (feeNote.getReportDate() == null) {
                    data.put("feeDate", "unknow");
                } else {
                    data.put("feeDate", DateUtils.dateTime(feeNote.getReportDate()));
                }
                if (feeNote.getContactPerson() == null) {
                    data.put("feeIntro", "unknow");
                } else {
                    data.put("feeIntro", feeNote.getContactPerson());
                }
                if (feeNote.getPositionTitle() == null) {
                    data.put("feePos", "unknow");
                } else {
                    data.put("feePos", feeNote.getPositionTitle());
                }
//                if (feeNote.getReportDate() == null) {
//                    data.put("cDate", "unknow");
//                } else {
//                    data.put("cDate", DateUtils.dateTime(feeNote.getReportDate()));
//                }
                if (feeNote.getReportDate() == null) {
                    data.put("cDate", "unknow");
                } else {
                    data.put("cDate", DateUtils.dateTime(feeNote.getReportDate()));
                }
                data.put("phone", sysUser.getPhonenumber());
                data.put("contactName", sysUser.getUserName());
                data.put("contactEmail", sysUser.getEmail());
                data.put("moneyStr", "(HK DOLLER " + NumberParserUtils.parse(String.valueOf(feeNote.getFeeAmt())).toUpperCase() + ")");
                // 7遍历data 给pdf表单表格赋值
                for (String key : data.keySet()) {
                    form.setField(key, data.get(key).toString());
                }
                ps.setFormFlattening(true);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    ps.close();
                    reader.close();
                    os.close();
                    Map result = new HashMap();
                    result.put("filename", "note_" + timeStr + ".pdf");
                    return success(result);
                } catch (Exception e) {
                    e.printStackTrace();
                    return error("下载失败");
                }
            }

        } else {
            return error("下载失败");
        }
    }

    @GetMapping("/downloadYearOrMon/{id}")
    public AjaxResult downloadYearOrMon(@PathVariable("id") Long id) throws IOException {
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (sysUser == null) {
            return error("当前用户不存在");
        }
        FeeNote feeNote = feeNoteService.selectFeeNoteById(id);
        if (feeNote != null) {
//            String inputFileName = RuoYiConfig.getDownloadPath() + "fee_model_fixzxc123.pdf";
            String inputFileName = RuoYiConfig.getDownloadPath() + "fee_model_month.pdf";
            if (feeNote.getMonType() == 1) {
                inputFileName = RuoYiConfig.getDownloadPath() + "fee_model_month.pdf";
            } else {
                inputFileName = RuoYiConfig.getDownloadPath() + "fee_model_year.pdf";
            }
            // 模板文件路径
            // 生成的文件路径
            String timeStr = System.currentTimeMillis() + "";
            timeStr = timeStr.substring(timeStr.length() - 5, timeStr.length());
            String outputFileName = RuoYiConfig.getDownloadPath() + "note_mon_annual_" + timeStr + ".pdf";
            OutputStream os = null;
            PdfStamper ps = null;
            PdfReader reader = null;
            PdfStamper stamper = null;

            try {
                os = new FileOutputStream(new File(outputFileName));
                // 2 读入pdf表单
                reader = new PdfReader(inputFileName);
                // 3 根据表单生成一个新的pdf
                ps = new PdfStamper(reader, os);
                // 4 获取pdf表单
                AcroFields form = ps.getAcroFields();
                // 5给表单添加中文字体
                BaseFont bf = BaseFont.createFont("Font/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                form.addSubstitutionFont(bf);
                String fileName = "";
                if (!StringUtils.isBlank(feeNote.getFilePath())) {
                    URI uri = new URI(feeNote.getFilePath());
                    fileName = uri.getPath().substring(uri.getPath()
                            .lastIndexOf('/') + 1);
                }
                // 6查询数据================================================
                Map<String, Object> data = new HashMap<String, Object>();
                if (!StringUtils.isBlank(feeNote.getClientName())) {
                    data.put("company", feeNote.getClientName());
                } else {
                    data.put("company", "UnKnow");
                }
                if (!StringUtils.isBlank(feeNote.getAmount())) {
                    data.put("amount", NumberParserUtils.fmtMicrometer(feeNote.getAmount()));
                    data.put("monSal", NumberParserUtils.fmtMicrometer(feeNote.getAmount()));
                } else {
                    data.put("amount", NumberParserUtils.fmtMicrometer("0"));
                    data.put("monSal", NumberParserUtils.fmtMicrometer("0"));
                }
                if (!StringUtils.isBlank(feeNote.getAddressLine1())) {
                    data.put("address", feeNote.getAddressLine1());
                } else {
                    data.put("address", "unknow");
                }
                if (!StringUtils.isBlank(feeNote.getDiscounted())) {
                    data.put("discount", feeNote.getDiscounted() + "%");
                } else {
                    data.put("discount", 0);
                }
                if (!StringUtils.isBlank(feeNote.getFeeNo())) {
                    data.put("feeNo", feeNote.getFeeNo());
                } else {
                    data.put("feeNo", "unknow");
                }
                if (feeNote.getFeeAmt() == null) {
                    data.put("netAmount", NumberParserUtils.fmtMicrometer("0"));
                    data.put("netAmount2", "HK$" + NumberParserUtils.fmtMicrometer("0"));
                } else {
                    data.put("netAmount", NumberParserUtils.fmtMicrometer(String.valueOf(feeNote.getFeeAmt())));
                    data.put("netAmount2", "HK$" + NumberParserUtils.fmtMicrometer(String.valueOf(feeNote.getFeeAmt())));
                }
                //
                if (!StringUtils.isBlank(feeNote.getAttn())) {
                    data.put("name", feeNote.getAttn());
                } else {
                    data.put("name", "unknow");
                }
                if (feeNote.getReportDate() == null) {
                    data.put("feeDate", "unknow");
                } else {
                    data.put("feeDate", DateUtils.dateTime(feeNote.getReportDate()));
                }
                if (feeNote.getContactPerson() == null) {
                    data.put("feeIntro", "unknow");
                } else {
                    data.put("feeIntro", feeNote.getContactPerson());
                }
                if (feeNote.getPositionTitle() == null) {
                    data.put("feePos", "unknow");
                } else {
                    data.put("feePos", feeNote.getPositionTitle());
                }
//                if (feeNote.getReportDate() == null) {
//                    data.put("cDate", "unknow");
//                } else {
//                    data.put("cDate", DateUtils.dateTime(feeNote.getReportDate()));
//                }
                if (feeNote.getReportDate() == null) {
                    data.put("cDate", "unknow");
                } else {
                    data.put("cDate", DateUtils.dateTime(feeNote.getReportDate()));
                }
                data.put("phone", sysUser.getPhonenumber());
                data.put("contactName", sysUser.getUserName());
                data.put("contactEmail", sysUser.getEmail());
                data.put("moneyStr", "(HK DOLLER " + NumberParserUtils.parse(String.valueOf(feeNote.getFeeAmt())).toUpperCase() + ")");
                // 7遍历data 给pdf表单表格赋值
                for (String key : data.keySet()) {
                    form.setField(key, data.get(key).toString());
                }
                ps.setFormFlattening(true);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    ps.close();
                    reader.close();
                    os.close();
                    Map result = new HashMap();
                    result.put("filename", "note_mon_annual_" + timeStr  + ".pdf");
                    return success(result);
                } catch (Exception e) {
                    e.printStackTrace();
                    return error("下载失败");
                }
            }

        } else {
            return error("下载失败");
        }
    }

    /**
     * 查询【请填写功能名称】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:note:list')")
    @GetMapping("/list")
    public TableDataInfo list(FeeNote feeNote)
    {
        startPage();
        List<FeeNote> list = feeNoteService.selectFeeNoteList(feeNote);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
//    @PreAuthorize("@ss.hasPermi('system:note:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FeeNote feeNote)
    {
        List<FeeNote> list = feeNoteService.selectFeeNoteList(feeNote);
        ExcelUtil<FeeNote> util = new ExcelUtil<FeeNote>(FeeNote.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:note:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(feeNoteService.selectFeeNoteById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:note:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FeeNote feeNote)
    {
        feeNote.setCreateTime(new Date());
        feeNote.setCreateUserId(String.valueOf(getUserId()));
        return toAjax(feeNoteService.insertFeeNote(feeNote));
    }

    @Resource
    private ISysNoteCountService sysNoteCountService;

    /**
     * 修改【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:note:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody FeeNote feeNote)
    {
        SysUser sysUser = sysUserService.selectUserById(getUserId());
        feeNote.setUpdateTime(new Date());
        feeNote.setUpdateUserId(String.valueOf(getUserId()));
        if (feeNote.getStatus().equals("Pending")){
            //生成发票号
            //查询是否存在该月的发票记录
            String yearMon = DateUtils.getYearMon();
            SysNoteCount sysNoteCount = new SysNoteCount();
            sysNoteCount.setTime(yearMon);
            List<SysNoteCount> sysNoteCountList = sysNoteCountService.selectSysNoteCountList(sysNoteCount);
            int count = 1;
            if (sysNoteCountList != null && sysNoteCountList.size() > 0) {
                SysNoteCount sct = sysNoteCountList.get(0);
                count = sct.getCount().intValue();
                count++;
                sct.setCount(Long.valueOf(count));
                sct.setUpdateBy(getUsername());
                sct.setUpdateTime(new Date());
                int updateSysNoteCount = sysNoteCountService.updateSysNoteCount(sct);
                if (updateSysNoteCount <= 0) {
                    throw new ServiceException("update count error");
                }
            } else {
                // 数据库插入一条
                SysNoteCount snc = new SysNoteCount();
                snc.setTime(yearMon);
                snc.setCount(Long.valueOf(count));
                snc.setCreateBy(getUsername());
                snc.setCreateTime(new Date());
                int insertSysNoteCount = sysNoteCountService.insertSysNoteCount(snc);
                if (insertSysNoteCount <= 0) {
                    throw new ServiceException("insert count error");
                }
            }
            String formattedCount = String.format("%03d", count);
            //发票序号：年（00）+月（00）+开单顺序号（000）+开单人简写（XX）（例：202401001EZ）
            String noteNo = yearMon + formattedCount + sysUser.getShorthand();
            feeNote.setFeeNo(noteNo);
            feeNote.setCheckDate(new Date());
        }
        return toAjax(feeNoteService.updateFeeNote(feeNote));
    }

    public static void main(String[] args) {
        String formattedCount = String.format("%03d", 10);
        System.out.println(formattedCount);
    }

    /**
     * 删除【请填写功能名称】
     */
//    @PreAuthorize("@ss.hasPermi('system:note:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(feeNoteService.deleteFeeNoteByIds(ids));
    }
}
